package org.dzms.commons;

import java.io.FileInputStream;
import java.lang.annotation.Retention;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;



public class DataHandler {
	private static DbManager dbm = new DbManager();
	
	private DataHandler(){}

	public static int update(String sql, Object[] params) {
		return dbm.update(sql, params);
	}
	
	public static <E>List<E> query(String sql, Object[] params, Class cls) {
		ResultSet rs = dbm.query(sql, params);
		List<E> lists = new ArrayList<E>();
		try {
			while (rs.next()) {
				Object obj = cls.newInstance();
				Field[] fields = cls.getDeclaredFields();
				for (Field field : fields) {
					field.setAccessible(true);
					String typeName = field.getType().getSimpleName();
					if (typeName.equalsIgnoreCase("string")) {
						field.set(obj, rs.getString(field.getName()));
					}else if (typeName.equalsIgnoreCase("int") || typeName.equals("integer")) {
						field.setInt(obj, rs.getInt(field.getName()));
					}else if (typeName.equalsIgnoreCase("long")) {
						field.setLong(obj, rs.getLong(field.getName()));
					}else if (typeName.equalsIgnoreCase("double")) {
						field.setDouble(obj, rs.getDouble(field.getName()));
					}else if (typeName.equalsIgnoreCase("date")) {
						field.set(obj, rs.getDate(field.getName()));
					}else if (typeName.equalsIgnoreCase("float")) {
						field.setFloat(obj, rs.getFloat(field.getName()));
					}
				}
				lists.add((E)obj);
			}
			rs.close();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return lists;
	}
	
	public static Object uniqueQuery(String sql, Object[] params) {
		ResultSet rs = dbm.query(sql, params); 
		Object obj = null;
		try {
			if (rs.next()) {
				obj = rs.getObject(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
